using System;
using System.Text;
using Microsoft.BizTalk.ExplorerOM;

namespace Conducido.Utils.Bts2006.BTSApplicationUtil.Presentation.ConsoleUI
{
    class Program
    {
        private static string ApplicationName;
        private static bool Start = false;
        private static bool argCheck = false;
        private static bool terminateAll = false;
        private static bool resumeAll = false;
        private static bool showAllApplications = false;
        private static bool showAllApplicationsWithStatus = false;

        static void Main(string[] args)
        {
            ParseCommandLine(args);
            if (argCheck)
            {
                try
                {
                    Application application;

                    BtsCatalogExplorer explorer = CreateBtsCatalogExplorer();
                    
                    if (showAllApplications == true)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("All BizTalk application:");
                        Console.ForegroundColor = ConsoleColor.White;
                        foreach (string applicationname in BtsInstancesHelper.ShowAllApplications(explorer))
                        {
                            Console.WriteLine(applicationname);
                        }
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }

                    else if (showAllApplicationsWithStatus == true)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine("All BizTalk application:");
                        Console.ForegroundColor = ConsoleColor.White;
                        foreach (string applicationname in BtsInstancesHelper.ShowAllApplicationsWithStatus(explorer))
                        {
                            Console.WriteLine(applicationname);
                        }
                        Console.ForegroundColor = ConsoleColor.Gray;
                    }

                    else
                    {
                        ApplicationCollection applications = explorer.Applications;
                        application = applications[ApplicationName];
                        if (application != null)
                        {
                            if (Start)
                            {
                                Console.WriteLine(string.Format("Starting BizTalk application: {0}", ApplicationName));
                                application.Start(ApplicationStartOption.StartAll);
                                if (resumeAll)
                                {
                                    Console.WriteLine("Resuming all suspended instances");
                                    BtsInstancesHelper.ResumeAllInstances(application);
                                }
                            }

                            else
                            {
                                Console.WriteLine(string.Format("Stopping BizTalk application: {0}", ApplicationName));
                                // terminate all instances for all orchestration in application
                                if (terminateAll)
                                {
                                    Console.WriteLine("Terminating all instances");
                                    BtsInstancesHelper.TerminateAllInstances(application);
                                }
                                application.Stop(ApplicationStopOption.StopAll);
                            }
                            Console.WriteLine("Saving changes to BizTalk Db....");
                            explorer.SaveChanges();
                            Console.WriteLine("Refreshing...");
                            explorer.Refresh();
                            string action = "Stop";
                            if (Start)
                            {
                                action = "Start";
                            }
                            Console.WriteLine(string.Format("Done application {1}: {0}", ApplicationName, action));
                        }
                        else
                        {
                            Console.WriteLine("{0} does not exist in database", ApplicationName);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
            else
            {
                Console.WriteLine("No application name has been provided");
            }
        }

        private static BtsCatalogExplorer CreateBtsCatalogExplorer()
        {
            BtsCatalogExplorer explorer = new BtsCatalogExplorer();
            explorer.ConnectionString = BtsConfigDbHelper.BtsConfigurationDatabase.GetConnectionString();
            return explorer;
        }

        static void ParseCommandLine(string[] args)
        {
            if (args.Length == 0)
            {
                // Nothing is entered      
                Console.WriteLine(HelpText());
            }


            foreach (string currentParam in args)
            {
                if (currentParam.ToLower() == "start")
                {
                    Start = true;
                }
                else if (currentParam.ToLower() == "stop")
                {
                    Start = false;
                }
                else if (currentParam.ToLower().Contains("applicationname"))
                {
                    argCheck = true;
                    ApplicationName = currentParam.Split(':')[1];
                }
                else if (currentParam.ToLower().Contains("terminateall"))
                {
                    terminateAll = true;
                }
                else if (currentParam.ToLower().Contains("resumeall"))
                {
                    resumeAll = true;
                }
                else if (currentParam.ToLower() == "showall")
                {
                    argCheck = true; //this option doens't need any other additional options
                    showAllApplications = true;
                }
                else if (currentParam.ToLower().Contains("showallwithstatus"))
                {
                    argCheck = true;
                    showAllApplicationsWithStatus = true;
                }
                else if (currentParam.ToLower().Contains("?"))
                {
                    // Nothing is entered
                    Console.WriteLine(HelpText());
                }
            }
        }


        /// <summary>
        /// Provides basic help text.
        /// </summary>
        /// <returns>Basic helptext</returns>
        static string HelpText()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("To start or stop an BizTalk application use the following commandline:");
            sb.AppendLine("BTSHostUtil.exe stop applicationname:<MYBizTalkApplicatin> <OPTIONAL>terminateall<OPTIONAL>");
            sb.AppendLine("If start option is used, you can also use resumeall to resume all suspended instances");
            sb.AppendLine("If server and database are not provided the default is local instance");
            sb.AppendLine("Note: This util only runs on the BizTalk server itself!\n");
            sb.AppendLine("Commands:");
            sb.AppendLine("-showall    ");
            sb.AppendLine("Shows all application on the host");
            sb.AppendLine("-showallwithstatus:");
            sb.AppendLine("Shows all application on the host with it current state (NA/Stopped/Started)");
            return sb.ToString();
        }
    }
}